const express = require("express");
const md5 = require("md5");
const UserModel = require("../../models/UserModel");
const router = express.Router();

router.get("/reg", (req, res) => {
  res.render("auth/reg");
});

router.post("/reg", (req, res) => {
  const { username, password } = req.body;
  // md5: 单向加密,只能通过原始值加密成密文,不能通过密文解密成原始值,后续校验可以将用户的 password 加密和数据库匹配
  UserModel.create({ username, password: md5(password) }, (err, data) => {
    if (err) {
      return res.status(500).send("注册失败,请稍后再试");
    }

    res.render("success", { msg: "注册成功", url: "/login" });
  });
});

router.get("/login", (req, res) => {
  res.render("auth/login");
});

router.post("/login", (req, res) => {
  const { username, password } = req.body;
  UserModel.findOne({ username, password: md5(password) }, (err, data) => {
    if (err) {
      return res.status(500).send("登录失败");
    }

    // 数据库没有查询到该数据
    if (!data) {
      return res.send("账号或密码错误");
    }

    // 登录成功逻辑
    req.session.username = data.username;
    req.session._id = data._id;

    res.render("success", { msg: "登录成功", url: "/account" });
  });
});

// 退出登录
router.post("/logout", (req, res) => {
  req.session.destroy(() => {
    res.render("success", { msg: "退出登录成功", url: "/login" });
  });
});

module.exports = router;
